import { computed, ref } from "vue";
export default function useShortcut(props, groupRef, currentIndex) {
  const ANCHOR_HEIGHT = 18;
  const scrollRef = ref(null);
  /*
  第一步:获取title数组 
   */
  const shortcutList = computed(() => {
    return props.data.map((item) => {
      return item.title;
    });
  });
  const touch = {};
  /* 
  第二步:touch事件
  */
  function onShortcutTouchStart(e) {
    //通过dom的dataset获取索引
    const anchorIndex = parseInt(e.target.dataset.index);
    touch.y1 = e.touches[0].pageY;
    touch.anchorIndex = anchorIndex;

    scrollTo(anchorIndex);
  }
  function onShortcutTouchMove(e) {
    touch.y2 = e.touches[0].pageY;
    const delta = ((touch.y2 - touch.y1) / ANCHOR_HEIGHT) | 0;
    const anchorIndex = touch.anchorIndex + delta;

    scrollTo(anchorIndex);
  }
  //滚动到index处
  function scrollTo(index) {
    if (isNaN(index)) {
      return;
    }
    index = Math.max(0, Math.min(shortcutList.value.length - 1, index));
    const targetEl = groupRef.value.children[index];
    const scroll = scrollRef.value.scroll;
    scroll.scrollToElement(targetEl, 0);
  }
  return {
    shortcutList,
    onShortcutTouchStart,
    onShortcutTouchMove,
    scrollRef,
  };
}
